package com.cyandpos.pad.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.changyi.device.printer.PrintManagerLib;
import com.cyandpos.pad.R;
import com.cyandpos.pad.bankpay.BankFunctionConstant;
import com.cyandpos.pad.bankpay.BankpayManger;
import com.cyandpos.pad.bankpay.R_BankData;
import com.cyandpos.pad.bankpay.bankImpl.BOC_BeiJing_Function;
import com.cyandpos.pad.cateringformat.CateringMainActivity;
import com.cyandpos.pad.common.commondata.BaseResponse;
import com.cyandpos.pad.common.commondata.Constant;
import com.cyandpos.pad.common.commondata.ConstantString;
import com.cyandpos.pad.common.commondata.DialogConstant;
import com.cyandpos.pad.common.commondata.ErpCommonData;
import com.cyandpos.pad.common.commondata.OnDialogListener;
import com.cyandpos.pad.common.commondata.PaymentIdConstant;
import com.cyandpos.pad.common.commondata.SktConfigConstant;
import com.cyandpos.pad.common.commondata.SktConfigIdCrmConstant;
import com.cyandpos.pad.common.netmanager.PosHttpManager;
import com.cyandpos.pad.common.swipemanager.SwipeCardCommon;
import com.cyandpos.pad.common.ticketformat.TicketFormat;
import com.cyandpos.pad.http.OkHttpUtils;
import com.cyandpos.pad.login.configs.GetConfigs;
import com.cyandpos.pad.netdata.R_Addpay;
import com.cyandpos.pad.pay.adapter.DepositUseAdapter;
import com.cyandpos.pad.pay.adapter.GoodsAdapter;
import com.cyandpos.pad.pay.adapter.O2oItemsAdapter;
import com.cyandpos.pad.pay.adapter.PayGridAdapter;
import com.cyandpos.pad.pay.adapter.PayListAdapter;
import com.cyandpos.pad.pay.adapter.RefundPayListAdapter;
import com.cyandpos.pad.pay.payList.Alipay;
import com.cyandpos.pad.pay.payList.JHAllPay;
import com.cyandpos.pad.pay.payList.WechatPay;
import com.cyandpos.pad.pay.presenter.CashCollectionPresenter;
import com.cyandpos.pad.pay.presenter.CustomerPaymentPresenter;
import com.cyandpos.pad.pay.presenter.PayNetRequestPresenter;
import com.cyandpos.pad.pay.ui.TimeThread;
import com.cyandpos.pad.pay.view.ICashCollectionView;
import com.cyandpos.pad.pay.view.ICustomerPaymentView;
import com.cyandpos.pad.pay.view.IPayNetRequestView;
import com.cyandpos.pad.posdata.CardCouponItem;
import com.cyandpos.pad.posdata.CashCardItem;
import com.cyandpos.pad.posdata.CodeCoupon;
import com.cyandpos.pad.posdata.ConsumeCrmPayData;
import com.cyandpos.pad.posdata.Coupon;
import com.cyandpos.pad.posdata.DepositUseData;
import com.cyandpos.pad.posdata.DjdInfo;
import com.cyandpos.pad.posdata.Goods;
import com.cyandpos.pad.posdata.Member;
import com.cyandpos.pad.posdata.O2OPayDetail;
import com.cyandpos.pad.posdata.OfferCoupon;
import com.cyandpos.pad.posdata.Order;
import com.cyandpos.pad.posdata.PayInfo;
import com.cyandpos.pad.posdata.Payment;
import com.cyandpos.pad.posdata.QueryMemberRequest;
import com.cyandpos.pad.posdata.RefundOrder;
import com.cyandpos.pad.posdata.Sktconfig;
import com.cyandpos.pad.posdata.TicketInfo;
import com.cyandpos.pad.posdata.YhkCardItem;
import com.cyandpos.pad.presentation.AdPresentationUtil;
import com.cyandpos.pad.sale.saleutils.SaleUtil;
import com.cyandpos.pad.sale.view.SelfNumKeyView;
import com.cyandpos.pad.utils.AppManager;
import com.cyandpos.pad.utils.ComSharedPreferences;
import com.cyandpos.pad.utils.CommonUtils;
import com.cyandpos.pad.utils.ConsumeConstant;
import com.cyandpos.pad.utils.MoneyUtils;
import com.cyandpos.pad.utils.OrderType;
import com.cyandpos.pad.utils.PayUtil;
import com.cyandpos.pad.utils.ToastUtils;
import com.cyandpos.pad.utils.log.MessageLog;
import com.cyandpos.pad.utils.log.LogUtils;
import com.cyandpos.pad.utils.log.SDTools;
import com.cyandpos.pad.utils.view.CouponMessageDialogCommon;
import com.cyandpos.pad.utils.view.InputNumberDialogCommon;
import com.cyandpos.pad.utils.view.SelectDialogCommon;
import com.google.gson.JsonObject;

import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;

import butterknife.BindView;

public class PayActivity extends BaseActivity implements View.OnClickListener,ICashCollectionView,ICustomerPaymentView,IPayNetRequestView , SwipeCardCommon.DoAfterSwipeCard {
    @BindView(R.id.tv_main_title_version)
    TextView tvMainTitleVersion;
    @BindView(R.id.tv_main_title_cashier)
    TextView tvMainTitleCashier;
    @BindView(R.id.tv_main_title_sktno)
    TextView tvMainTitleSktno;
    @BindView(R.id.tv_main_title_orderno)
    TextView tvMainTitleOrderno;
    @BindView(R.id.tv_main_title_currentTime)
    public TextView tvMainTitleCurrentTime;
    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.tv_title_refund)
    TextView tv_title_refund;
    @BindView(R.id.tv_pay_money_name)
    TextView tv_pay_money_name;
    @BindView(R.id.tv_wait_pay)
    TextView tv_wait_pay;
    @BindView(R.id.tv_collect_money_name)
    TextView tv_collect_money_name;
    @BindView(R.id.tv_good_price)
    TextView tv_good_price;
    @BindView(R.id.tv_discount_price)
    TextView tv_discount_price;
    @BindView(R.id.tv_pay_money)
    TextView tv_pay_money;
    @BindView(R.id.tv_collect_money)
    TextView tv_collect_money;
    @BindView(R.id.tv_wait_pay_money)
    TextView tv_wait_pay_money;
    @BindView(R.id.tv_change_money)
    TextView tv_change_money;
    @BindView(R.id.lv_act_payList)
    ListView lvActPayList;
    @BindView(R.id.gv_act_pay)
    GridView gvActPay;
    @BindView(R.id.lv_main_goodList)
    ListView lv_main_goodList;
    @BindView(R.id.btn_act_pay_confirm)
    TextView btn_act_pay_confirm;
    @BindView(R.id.tv_no_vip)
    TextView tv_no_vip;
    @BindView(R.id.ll_vip)
    LinearLayout ll_vip;
    @BindView(R.id.tv_vip_name)
    TextView tv_vip_name;
    @BindView(R.id.tv_vip_type)
    TextView tv_vip_type;
    @BindView(R.id.tv_vip_cent)
    TextView tv_vip_cent;
    @BindView(R.id.listview_pay)
    ListView listview_pay;
    @BindView(R.id.ll_refund_pay)
    LinearLayout ll_refund_pay;
    public TicketInfo mTicket;  //小票
    public int saleType = -1;// 0:销售，1：退货
    private int returnNeedBuyCentMoney = 0;// 需要钱买分的金额
    private boolean isNeedBuyCent = false;// 是否需要钱买分
    public PayListAdapter payListAdapter = null;//收款方式adapter
    public PayGridAdapter payAdapter = null;//付款方式adapter
    public GoodsAdapter goodsAdapter;
    private List<Goods> goodsLists;//退货显示的商品列表
    private int mSelectedPmtId = -1;
    private int mSelectedPmtZlclfs = 0;//当前付款方式的找零处理方式
    private int payType = -1;
    private int mPosition = -1;
    Payment mSelectPay =null;

    private int currentPay;//当前付款金额
    private int allPayMoney;//总付款金额
    private String waitPayMoney;//待付金额
    private List<Payment> payItemList;//付款方式列表
    private Payment payItem;//当前付款方式
    private boolean needWait = false;//是否正在交易
    public PayNetRequestPresenter netPresenter;
    private AlertDialog mDialog;//所有dialog
    private int vipCardToGrantCount = 0;//返券后刷卡取消次数
    private ProgressDialog mProgressDialog;//等待框
    private String name="";
    private int currentDelPayCode = -1;
    private int currentDelPayType = -1;
    private boolean isDeletePayRequestAddpay = false;//是否是删除付款方式请求同步付款接口

    private boolean clearAllPay = false;//是否按返回键

    public boolean isWxOrZfBBL = false;
    private final MyHandler handler = new MyHandler(this);
    private List<Goods> goodsList;
    private AdPresentationUtil adPresentationUtil;
    private int fromType=0;
    //订金单使用
    private List<DepositUseData> depositList;
    private DepositUseAdapter depositUseAdapter;
    public ProgressDialog fastTradingProgress;//等待框
    ArrayList<YhkCardItem> yhkCardList=new ArrayList<>();
    public class MyHandler extends Handler {
        private final WeakReference<PayActivity> mActivity;

        public MyHandler(PayActivity activity) {
            this.mActivity = new WeakReference<PayActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            PayActivity payActivity = mActivity.get();
            if (payActivity == null) {
                return;
            }
            switch (msg.what) {
                case 3900: {//删除收款方式
                    payActivity.isDeletePayRequestAddpay = true;
                    payActivity.currentDelPayCode = msg.arg1;
                    payActivity.currentDelPayType = msg.arg2;
                    if(payActivity.currentDelPayType == Payment.SKFS_YHQK){
                        boolean isCodeCoupon = false;
                        for(Payment item :payActivity.mTicket.getPayList()){
                            if(item.getPayCode() == payActivity.currentDelPayCode){
                                if(item.getIsCoded()==1){
                                    isCodeCoupon = true;
                                }
                            }
                        }
                        if(isCodeCoupon){
                            payActivity.codedCouponHandleData(1);
                        }else{
                            payActivity.cardCouponHandleData(1);
                        }
                    }else{
                        if(payActivity.currentDelPayType == Payment.SKFS_DJD){
                            payActivity.depositList.clear();
                            payActivity.mTicket.getDepositUsedList().clear();
                        }
                        payActivity.payItem.setPayAmount(MoneyUtils.getMoneyStr(0));
                        payActivity.payItem.setPayCode(payActivity.currentDelPayCode);
                        payActivity.payItem.setPayType(payActivity.currentDelPayType);
                        payActivity.payItemList.clear();
                        payActivity.payItemList.add(payActivity.payItem);
                        payActivity.netPresenter.saveAddpayRequest(payActivity.mTicket.getOrderNo(), payActivity.payItemList, payActivity.saleType,false); // 同步付款 （确认支付调用）

                    }
                }
                break;
                case Constant.MAIN_UPDATE_CURRENT_TIME_HANDLEID:
                    String time = msg.getData().getString("time");
                    tvMainTitleCurrentTime.setText(time);
                    break;
                case 101:
                    payActivity.reqAddpayNet(new BigDecimal(mTicket.getDecPreferentialMoney()).multiply(new BigDecimal(100)).intValue(),false);// 同步付款 （确认支付调用）
                    break;
            }

        }

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pay;
    }

    @Override
    protected void initData() {
        depositList = new ArrayList<>();
        goodsList=new ArrayList<>();
        mTicket = ErpCommonData.ticketInfo;
        setAdPresentation(1);
        tvMainTitleVersion.setText(CommonUtils.getCurrentVersionName(PayActivity.this));
        tvMainTitleCashier.setText(ErpCommonData.loadConfig.getCashierName() + "");
        tvMainTitleSktno.setText(ErpCommonData.sktno + "");
        tvMainTitleOrderno.setText(ErpCommonData.orderNo + "");
        TimeThread timeThread = new TimeThread(handler,0);
        timeThread.setDaemon(true);//守护线程
        timeThread.start();
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setCancelable(false);
        fastTradingProgress = new ProgressDialog(this);
        fastTradingProgress.setCancelable(false);
        fastTradingProgress.setMessage("交易中请等待");
        payItemList = new ArrayList<>();
        goodsLists = new ArrayList<>();
        payItem = new Payment();
        Bundle bd = getIntent().getExtras();
        saleType = bd.getInt("SaleType", 0);// 0:销售，1：退货
        isNeedBuyCent = bd.getBoolean("isNeedBuyCent",false);
        returnNeedBuyCentMoney = bd.getInt("buyCentMoney",0);
        fromType= bd.getInt("fromType",0);//是否餐饮
        payListAdapter = new PayListAdapter(PayActivity.this, mTicket.getPayList(), handler);
        lvActPayList.setAdapter(payListAdapter);//付款方式列表
        new CashCollectionPresenter(this).getPaymentList();//获取收款方式
        netPresenter = new PayNetRequestPresenter(this);//各种网络请求
        mDialog = new ProgressDialog(PayActivity.this);

        if (saleType == 1){
            if(mTicket.getSubTickets()!=null&&mTicket.getSubTickets().size()>0) {
                for (int i = 0; i < mTicket.getSubTickets().size(); i++) {
                    for (int j = 0; j < mTicket.getSubTickets().get(i).getGoodsList().size(); j++) {
                        Goods goods = mTicket.getSubTickets().get(i).getGoodsList().get(j);
                        if(mTicket.isFSTH()){
                            goodsLists.add(goods);
                        }else {
                            if (CommonUtils.getInt(goods.getRefundCount()) != 0) {
                                goodsLists.add(goods);
                            }
                        }
                    }
                }
            }
        }else {
            goodsLists.clear();
            if(mTicket.getSubTickets()!=null&&mTicket.getSubTickets().size()>0) {
                for (int i = 0; i < mTicket.getSubTickets().size(); i++) {
                    goodsLists.addAll(mTicket.getSubTickets().get(i).getGoodsList());
                }
            }
        }

        goodsAdapter=new GoodsAdapter(PayActivity.this,goodsLists);
        lv_main_goodList.setAdapter(goodsAdapter);

        if (saleType == 1) {//退货
            tv_title_refund.setVisibility(View.VISIBLE);
            tv_collect_money_name.setText("已退金额：");
            tv_pay_money_name.setText("应退金额：");
            tv_wait_pay.setText("待退金额：");
            ll_refund_pay.setVisibility(View.VISIBLE);
            ll_vip.setVisibility(View.GONE);
            tv_no_vip.setVisibility(View.GONE);
            if(ErpCommonData.oldTicket.getPayList()!=null&&ErpCommonData.oldTicket.getPayList().size()>0) {
                RefundPayListAdapter refundPayListAdapter = new RefundPayListAdapter(PayActivity.this, ErpCommonData.oldTicket.getPayList());
                listview_pay.setAdapter(refundPayListAdapter);
            }else{
                if(ErpCommonData.ticketInfo.getPayList()!=null&&ErpCommonData.ticketInfo.getPayList().size()>0) {
                    RefundPayListAdapter refundPayListAdapter = new RefundPayListAdapter(PayActivity.this, ErpCommonData.ticketInfo.getPayList());
                    listview_pay.setAdapter(refundPayListAdapter);
                }
            }
            //判断原交易是否有用券信息
            oldTicketYHQInfo();
            //判断原交易有返券信息，但退货时券不足的情况
            oldTicketOfferCouponsLack();
            //判断退货交易是否需要钱买分
            returnTradeIsNeedMoneyBuyCent();
        } else {//销售
            tv_title_refund.setVisibility(View.GONE);
            tv_collect_money_name.setText("已收金额：");
            tv_pay_money_name.setText("应付金额：");
            tv_wait_pay.setText("待付金额：");
            Member member=mTicket.getMemberInfo();
            if(member!=null){
                ll_refund_pay.setVisibility(View.GONE);
                ll_vip.setVisibility(View.VISIBLE);
                tv_no_vip.setVisibility(View.GONE);
                tv_vip_name.setText(member.getMemberName());
                tv_vip_type.setText(member.getMemberCardTypeName());
                tv_vip_cent.setText(member.getMemberCardValidCent());
            }else{
                ll_refund_pay.setVisibility(View.GONE);
                ll_vip.setVisibility(View.GONE);
                tv_no_vip.setVisibility(View.VISIBLE);
            }
        }
        allPayMoney=mTicket.getTotalMoney();
        waitPayMoney=MoneyUtils.getMoneyStr(mTicket.getTotalMoney() - mTicket.getHasPayed());
        CalculatorPayed();
        iv_back.setOnClickListener(new View.OnClickListener() {//标题返回按钮
            @Override
            public void onClick(View v) {
//                showBackDialog();
                if(mTicket.getHasPayed()>=mTicket.getTotalMoney()){
                    reqCommitNet();
                }else{
                    showBackDialog();
                }
            }
        });
        btn_act_pay_confirm.setOnClickListener(this);
        fullMortgage();
    }

    public void reqCommitNet(){
        fastTradingProgress.show();
        netPresenter.saveCommitPayRequest(mTicket,false);
    }


    private void returnTradeIsNeedMoneyBuyCent() {
        if(isNeedBuyCent){
            payItemList.clear();
            payItem.setPayAmount(MoneyUtils.getMoneyStr(returnNeedBuyCentMoney));
            for(Payment p :ErpCommonData.loadConfig.getPayList()){
                if(p.getPayType() == Payment.SKFS_QMF){
                    payItem.setPayCode(p.getPayCode());
                    payItem.setPayType(Payment.SKFS_QMF);
                    break;
                }
            }
            payItemList.add(payItem);
            payType = Payment.SKFS_QMF;
            mSelectedPmtId = payItem.getPayCode();
            currentPay = returnNeedBuyCentMoney;
            netPresenter.saveAddpayRequest(mTicket.getOrderNo(), payItemList,saleType,false); // 同步付款 （确认支付调用）
        }
    }
    public void fullMortgage(){
        //是否有满抵
        if(mTicket.getDecPreferentialMoney()!=null &&!"".equals(mTicket.getDecPreferentialMoney())){
            if(Math.abs(MoneyUtils.getMoneyInt(mTicket.getDecPreferentialMoney()))>0){
                for(int i=0;i<ErpCommonData.loadConfig.getPayList().size();i++){
                    if(ErpCommonData.loadConfig.getPayList().get(i).getPayType() == Payment.SKFS_MBDY){
                        mSelectedPmtId = ErpCommonData.loadConfig.getPayList().get(i).getPayCode();
                        mSelectedPmtZlclfs = ErpCommonData.loadConfig.getPayList().get(i).getChangeType();
                        payType = ErpCommonData.loadConfig.getPayList().get(i).getPayType();
                        currentPay=Math.abs(MoneyUtils.getMoneyInt(mTicket.getDecPreferentialMoney()));
                        break;
                    }
                }
                if (payType != Payment.SKFS_MBDY){
                    ToastUtils.showMsg(PayActivity.this,"请先配置满百抵用收款方式!");
                    return;
                }
                //生成收款方式
                new CustomerPaymentPresenter(this, mSelectedPmtId, payType, currentPay).addCustomerPayment();
            }
        }
    }
    private void oldTicketOfferCouponsLack() {
        if (ErpCommonData.oldTicket.getOfferCouponList() != null &&
                ErpCommonData.oldTicket.getOfferCouponList().size() > 0) {
            int different = 0;
            for (OfferCoupon o : ErpCommonData.oldTicket.getOfferCouponList()) {
                different += MoneyUtils.getMoneyInt(o.getDifference());
            }
            if (different > 0) {
                Payment payFQBC = null;
                for (Payment e : ErpCommonData.loadConfig.getPayList()) {
                    if (e.getPayType() == Payment.SKFS_FQBC) {
                        payFQBC = e;
                        break;
                    }
                }
                if (payFQBC == null) {
                    showCouponsBackDialog();
                    return;
                }
                payFQBC.setPayAmount(MoneyUtils.getMoneyStr(different));
                payItemList.clear();
                payItem.setPayAmount(MoneyUtils.getMoneyStr(different));
                payItem.setPayCode(payFQBC.getPayCode());
                payItem.setPayType(Payment.SKFS_FQBC);
                payItemList.add(payItem);
                payType = Payment.SKFS_FQBC;
                mSelectedPmtId = payFQBC.getPayCode();
                currentPay = different;
                netPresenter.saveAddpayRequest(mTicket.getOrderNo(), payItemList,saleType,false); // 同步付款 （确认支付调用）
            }
        }
    }

    private void oldTicketYHQInfo() {
        if (ErpCommonData.oldTicket.getCardCouponList() != null &&
                ErpCommonData.oldTicket.getCardCouponList().size() > 0) {
            mTicket.getCardCouponList().clear();
            mTicket.getCardCouponList().addAll(ErpCommonData.oldTicket.getCardCouponList());
            //请求同步付款
            payType=Payment.SKFS_YHQK;
            mSelectPay = new Payment();
            mSelectPay.setIsCoded(0);
            mSelectPay.setPayType(Payment.SKFS_YHQK);
            cardCouponHandleData(0);
        }

        if (ErpCommonData.oldTicket.getCodedCouponList() != null &&
                ErpCommonData.oldTicket.getCodedCouponList().size() > 0) {
            mTicket.getCodedCouponList().clear();
            mTicket.getCodedCouponList().addAll(ErpCommonData.oldTicket.getCodedCouponList());
            //请求同步付款
            payType=Payment.SKFS_YHQK;
            mSelectPay = new Payment();
            mSelectPay.setIsCoded(1);
            mSelectPay.setPayType(Payment.SKFS_YHQK);
            codedCouponHandleData(0);
        }
    }


    private void showBackDialog() {
        String titleMsg = "是否退出支付?";
        String messageMsg = saleType ==0 ?
                "如果使用 支付宝、微信等第三方收款方式时，请谨慎！":
                "如果已退 支付宝、微信等第三方收款方式后，请谨慎！";
        SaleUtil.showInfoDialog(PayActivity.this, titleMsg, messageMsg, new OnDialogListener() {
            @Override
            public void onClick(int flag) {
                if(flag== DialogConstant.DIALOG_BTN_SURE) {
                    clearAllPay = true;
                    reqAddpayNet(0,true);
//                        cancelTrade();
//                        finish();
                }
            }
        });
    }

    private void cancelTrade() {
        mTicket.setTotalDiscount(0.00+"");
        mTicket.setDecMoney(0.00+"");
        mTicket.setChangeAmount(0.00+"");
        mTicket.getCodedCouponList().clear();
        mTicket.getCardCouponList().clear();
        mTicket.getCashCardList().clear();
        mTicket.getO2oWxList().clear();
        mTicket.getO2oZfbList().clear();
        mTicket.getBankCardList().clear();
        yhkCardList.clear();
        depositList.clear();
        Iterator<Payment> iterator = mTicket.getPayList().iterator();
        while (iterator.hasNext()) {
            Payment p = iterator.next();
            iterator.remove();
        }
    }


    /**
     * 收款方式点击事件
     * @param imgs 默认图片
     * @param select_imgs 选中后图片
     * @param skfs 收款方式
     */
    @Override
    public void showPaymetListData(List<Integer> imgs, List<Integer> select_imgs,final List<Payment> skfs) {

        if(skfs.size()>7) {
            payAdapter = new PayGridAdapter(PayActivity.this, skfs.subList(0, 7), true);
        }else{
            payAdapter = new PayGridAdapter(PayActivity.this, skfs, false);
        }
        gvActPay.setAdapter(payAdapter);
        gvActPay.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                //判断付款金额是否足够
                int needMoney = mTicket.getTotalMoney() - mTicket.getHasPayed();
                if (Double.parseDouble(waitPayMoney) <= 0) {
                    ToastUtils.showMsg("支付金额已经足够");
                    return;
                }
                if(position==7){
                    payDialogMore(skfs.subList(7,skfs.size()));
                }else {
                    mSelectPay = skfs.get(position);
                    mSelectedPmtId = skfs.get(position).getPayCode();
                    mSelectedPmtZlclfs = skfs.get(position).getChangeType();
                    payType = skfs.get(position).getPayType();
                    mPosition = position;
                    payAdapter.setSelectPos(mPosition, true);
                    payTypeSubmit();
                }
            }
        });
    }

    private void showO2OTraceTypeZFB() {
        if(saleType ==1){//退货
            List<O2OPayDetail> currentZfbList = new ArrayList<>();
            for (Payment payment:ErpCommonData.oldTicket.getPayList()){
                for (PayInfo payInfo:payment.getPayInfoList()){
                    if (payInfo.getPay_code().equals(String.valueOf(mSelectedPmtId))){
                        O2OPayDetail item=new O2OPayDetail();
                        item.setOutTradeNo(payInfo.getOutTradeNo());
                        item.setTransactionId(payInfo.getTransactionId());
                        item.setJysj(payInfo.getPay_time());
                        item.setTotalFee(MoneyUtils.getMoneyInt(payInfo.getPay_amount())+MoneyUtils.getMoneyInt(payInfo.getPay_yhje())+MoneyUtils.getMoneyInt(payInfo.getPay_yhje_shop()));
                        currentZfbList.add(item);
                    }
                }
            }
            if(currentZfbList.size()>0){
                ErpCommonData.oldTicket.setO2oZfbList(currentZfbList);
                selectNeedReturnWXOrZFBOrLpqOrder(currentZfbList);
            }else{
                ToastUtils.showMsg("原交易没有此收款方式！");
                payAdapter.setSelectPos(mPosition, false);
            }
        }else{//消费
            payDialogCommon();
        }

    }

    private void showO2OTraceTypeWX() {
        if(saleType ==1){//退货
            List<O2OPayDetail> currentWxList = new ArrayList<>();
            for (Payment payment:ErpCommonData.oldTicket.getPayList()){
                for (PayInfo payInfo:payment.getPayInfoList()){
                    if (payInfo.getPay_code().equals(String.valueOf(mSelectedPmtId))){
                        O2OPayDetail item=new O2OPayDetail();
                        item.setOutTradeNo(payInfo.getOutTradeNo());
                        item.setTransactionId(payInfo.getTransactionId());
                        item.setJysj(payInfo.getPay_time());
                        item.setTotalFee(MoneyUtils.getMoneyInt(payInfo.getPay_amount())+MoneyUtils.getMoneyInt(payInfo.getPay_yhje())+MoneyUtils.getMoneyInt(payInfo.getPay_yhje_shop()));
                        currentWxList.add(item);
                    }
                }
            }
            if(currentWxList.size()>0){
                ErpCommonData.oldTicket.setO2oWxList(currentWxList);
                selectNeedReturnWXOrZFBOrLpqOrder(currentWxList);
            }else{
                ToastUtils.showMsg("原交易没有此收款方式！");
                payAdapter.setSelectPos(mPosition, false);
            }

        }else{//消费
            payDialogCommon();
        }
    }

    private void showO2OTraceTypeJH() {
        if(saleType ==1){//退货
            List<O2OPayDetail> currentJhList = new ArrayList<>();
            for (Payment payment:ErpCommonData.oldTicket.getPayList()){
                for (PayInfo payInfo:payment.getPayInfoList()){
                    if (payInfo.getPay_code().equals(String.valueOf(mSelectedPmtId))){
                        O2OPayDetail item=new O2OPayDetail();
                        item.setOutTradeNo(payInfo.getOutTradeNo());
                        item.setTransactionId(payInfo.getTransactionId());
                        item.setJysj(payInfo.getPay_time());
                        item.setTotalFee(MoneyUtils.getMoneyInt(payInfo.getPay_amount())+MoneyUtils.getMoneyInt(payInfo.getPay_yhje())+MoneyUtils.getMoneyInt(payInfo.getPay_yhje_shop()));
                        currentJhList.add(item);
                    }
                }
            }
            if(currentJhList.size()>0){
                ErpCommonData.oldTicket.setJhList(currentJhList);
                selectNeedReturnWXOrZFBOrLpqOrder(currentJhList);
            }else{
                ToastUtils.showMsg("原交易没有此收款方式！");
                payAdapter.setSelectPos(mPosition, false);
            }
        }else{//消费
            payDialogCommon();
        }

    }

    private void handleCZKTrade() {
        if(PayUtil.isReturnedTrade(mTicket)){//退货
            boolean isUsedCzk =false;
            for(Payment p : ErpCommonData.oldTicket.getPayList()){
                if(p.getPayType() == Payment.SKFS_CZK){
                    isUsedCzk =true;
                    break;
                }
            }
            if(isUsedCzk){
                JumpCashCardActivity();
            }else{
                ToastUtils.showMsg("原交易没有使用该收款方式！");
            }

        }else{
            JumpCashCardActivity();
        }
    }

    private void JumpCashCardActivity() {
        Intent intent = new Intent(PayActivity.this, PayCashCardActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("PAYMENTID", mSelectedPmtId);
        bundle.putInt("PAYTYPE", payType);
        intent.putExtras(bundle);
        startActivityForResult(intent, Constant.CZK_COMPLETED_ID);
    }

    private void showO2OTraceType() {//1  微信     2支付宝
        SelectDialogCommon selectDialogCommon=SelectDialogCommon.getSelectDialogCommon(PayActivity.this, new SelectDialogCommon.SelectDialogOnItemClickListener() {
            @Override
            public void selectDialogOnItemClick(int position) {
                   switch (position){
                       case 0:
                           if(saleType ==1){//退货
                               if(payType == Payment.SKFS_WX){//WX
                                   if(mTicket.isFSTH()){
                                       payDialogCommon();
                                   }else {
                                       showO2OTraceTypeWX();
                                   }
                               }else if(payType == Payment.SKFS_ZFB){//ZFB
                                   if(mTicket.isFSTH()){
                                       payDialogCommon();
                                   }else {
                                       showO2OTraceTypeZFB();
                                   }
                               }else if(payType == Payment.SKFS_JH){
                                   if(mTicket.isFSTH()){
                                       payDialogCommon();
                                   }else {
                                       showO2OTraceTypeJH();
                                   }
                               }
                           }else{//消费
                               payDialogCommon();
                           }
                           break;
                       case 1:
                           O2oBLStyle();
                           break;
                   }
            }
        });
        selectDialogCommon.setTitle("请选择交易类型");
        String [] titles=new String[2];
        titles[0]="正常交易";
        titles[1]="补录交易";
        selectDialogCommon.showDialog(titles,false);
    }

    private void O2oBLStyle() {
        String blFlag ="1";//补录类型——直接生成收款方式
        MessageLog.writeLog("补录是否直接生成收款方式标记blFlag："+blFlag);
        for(Sktconfig cItem: ErpCommonData.loadConfig.getSkt().getSktconfigList()){
            if(cItem.getLx().equals(SktConfigConstant.SKT_CONFIG_TYPE_PAYMENT) ){
                if(cItem.getId().equals(PaymentIdConstant.SKT_CONFIG_PAYMENT_SETTING_O2O_BL)){
                    blFlag = cItem.getValue();
                    break;
                }
            }
        }
        MessageLog.writeLog("补录是否直接生成收款方式标记blFlag："+blFlag);
        if(blFlag.equals(1+"")){//直接生成收款方式
            isWxOrZfBBL = true;
            payDialogCommon();
        }else if(blFlag.equals(2+"")){//输入商户订单号补录

            SelectDialogCommon selectDialogCommon=SelectDialogCommon.getSelectDialogCommon(PayActivity.this, new SelectDialogCommon.SelectDialogOnItemClickListener() {
                @Override
                public void selectDialogOnItemClick(int position) {
                    switch (position){
                        case 0:
                            showInputMerchantNoDialog();
                            break;
                        case 1:
                             Intent intent = new Intent(PayActivity.this, ScanCodeActivity.class);
                            startActivityForResult(intent, Constant.PAY_O2O_BL_SCANCODE_RESULTID);
                            break;
                    }
                }
            });
            selectDialogCommon.setTitle("请选择补录单号录入方式");
            String [] titles=new String[2];
            titles[0]="手动输入";
            titles[1]="扫码录入";
            selectDialogCommon.showDialog(titles,false);
        }

    }

    private void showInputMerchantNoDialog() {
        InputNumberDialogCommon inputNumberDialogCommon= InputNumberDialogCommon.getInputNumberDialogCommon(PayActivity.this, new InputNumberDialogCommon.InputDialogOnSubmitClickListener() {
            @Override
            public void InputDialogOnSubmitClick(String content) {
                if(content.equals("") || content==null){
                    ToastUtils.showMsg( "补录商户订单号不能为空");
                    return;
                }
                if(payType == Payment.SKFS_WX){//微信
                    new WechatPay(PayActivity.this,mTicket,mSelectedPmtId,0,content).o2oBl();
                }else if(payType == Payment.SKFS_ZFB){//支付宝
                    new Alipay(PayActivity.this,mTicket,mSelectedPmtId,0,content).o2oBl();
                }else if(payType == Payment.SKFS_JH){
                    new JHAllPay(PayActivity.this,mTicket,mSelectedPmtId,0,content).o2oBl();
                }
            }
        });
        inputNumberDialogCommon.setIsCanInputPoint(false);
        inputNumberDialogCommon.setTitle("请输入补录所需数据");
        inputNumberDialogCommon.setContent("请输入商户订单号");
        inputNumberDialogCommon.setEtHint("商户订单号");
        inputNumberDialogCommon.showDialog(false);
    }

    private void selectNeedReturnWXOrZFBOrLpqOrder(List<O2OPayDetail> itemList) {
        AlertDialog.Builder builder=new AlertDialog.Builder(PayActivity.this);
        final AlertDialog dialog=builder.create();
        dialog.setCancelable(false);
        View view= View.inflate(PayActivity.this, R.layout.pay_return_wxorzfb, null);
        RelativeLayout rl_close=view.findViewById(R.id.rl_close);
        ListView lv = view.findViewById(R.id.lv_wxorzfb);
        final O2oItemsAdapter adapter = new O2oItemsAdapter(itemList, PayActivity.this);
        lv.setAdapter(adapter);
        rl_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        //item的点击事件
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                dialog.dismiss();
                O2OPayDetail o2OItem = (O2OPayDetail) adapter.getItem(position);
                showO2OReturnPrintMoney(o2OItem);
            }
        });

        dialog.setView(view,0,0,0,0);
        dialog.show();
        dialog.getWindow().setBackgroundDrawableResource(R.drawable.dialog_bg_common);
    }

    //O2O输入退货金额
    private void showO2OReturnPrintMoney(final O2OPayDetail o2OItem) {

        InputNumberDialogCommon inputNumberDialogCommon= InputNumberDialogCommon.getInputNumberDialogCommon(PayActivity.this, new InputNumberDialogCommon.InputDialogOnSubmitClickListener() {
            @Override
            public void InputDialogOnSubmitClick(String content) {
                if(content.equals("") || content==null){
                    ToastUtils.showMsg( "输入内容不能为空！");
                    return;
                }
                currentPay = MoneyUtils.getMoneyInt(content.trim());
                if(payType ==Payment.SKFS_WX){//微信
                    new WechatPay(PayActivity.this,mTicket,mSelectedPmtId,currentPay,o2OItem.getOutTradeNo()).o2oConsume();

                }else if(payType ==Payment.SKFS_ZFB){//支付宝
                    new Alipay(PayActivity.this,mTicket,mSelectedPmtId,currentPay,o2OItem.getOutTradeNo()).o2oConsume();
                }else if (payType == Payment.SKFS_JH ){
                    new JHAllPay(PayActivity.this,mTicket,mSelectedPmtId,currentPay,o2OItem.getOutTradeNo()).o2oConsume();
                }
//                if(payType ==3){//礼品券
////                    new YGDZKpay(PayActivity.this,mTicket,mSelectedPmtId,currentPay,o2OItem.getOutTradeNo()).zfbConsume();
//                }else if(payType ==4){//woPay
////                    new WoPay(PayActivity.this,mTicket,mSelectedPmtId,currentPay,o2OItem.getOutTradeNo()).zfbConsume();
//                }
            }
        });
        inputNumberDialogCommon.setIsCanInputPoint(true);
        inputNumberDialogCommon.setTitle("退货金额");
        inputNumberDialogCommon.setContent("请输入退货金额");
        inputNumberDialogCommon.setEtHint("退货金额");
        inputNumberDialogCommon.setEtText(MoneyUtils.getMoneyStr(o2OItem.getTotalFee()));
        inputNumberDialogCommon.showDialog(false);


    }


    public void payDialogCommon(){
        AlertDialog.Builder builder=new AlertDialog.Builder(PayActivity.this);
        final AlertDialog payDialog=builder.create();
        payDialog.setCancelable(true);
        View view =LayoutInflater.from(PayActivity.this).inflate(R.layout.dialog_pay_common,null);
        TextView tv_price=view.findViewById(R.id.tv_dialog_pay);
        final EditText et_price=view.findViewById(R.id.et_price);
        final SelfNumKeyView sf_containt = view.findViewById(R.id.member_soft_keyboard);
        Button bt_submit=view.findViewById(R.id.bt_submit);
        RelativeLayout rl_close=view.findViewById(R.id.rl_close);
        et_price.setFocusable(false);
        et_price.setText(waitPayMoney);
        et_price.setSelection(et_price.getText().length());
        sf_containt.setIsCanInputPoint(true);
        sf_containt.setEnterReceptor(et_price);
        sf_containt.setIsClearEt(true);
        sf_containt.setOnCallBack(new SelfNumKeyView.SelfNumCallBack() {
            @Override
            public void keyBoardSure(String num,String hint) {
                paySubmit(et_price.getText() + "");
                payDialog.dismiss();
            }
        });
        rl_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                payDialog.dismiss();
            }
        });
        bt_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                paySubmit(et_price.getText() + "");
                payDialog.dismiss();
            }
        });
        tv_price.setText(waitPayMoney);
        payDialog.setView(view,0,0,0,0);
        payDialog.show();
        payDialog.getWindow().setBackgroundDrawableResource(R.drawable.dialog_bg_common);
        WindowManager.LayoutParams params = payDialog.getWindow().getAttributes();
        params.width = 900;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        payDialog.getWindow().setAttributes(params);
    }


    public void payDialogWZ(){
        InputNumberDialogCommon inputNumberDialogCommon= InputNumberDialogCommon.getInputNumberDialogCommon(PayActivity.this, new InputNumberDialogCommon.InputDialogOnSubmitClickListener() {
            @Override
            public void InputDialogOnSubmitClick(String content) {
                if(content.equals("") || content==null){
                    ToastUtils.showMsg( "请输入付款码");
                    return;
                }
                if (payType == Payment.SKFS_ZFB) {
                    new Alipay(PayActivity.this, mTicket, mSelectedPmtId, currentPay, content).o2oConsume();
                } else if (payType == Payment.SKFS_WX) {
                    new WechatPay(PayActivity.this, mTicket, mSelectedPmtId, currentPay, content).o2oConsume();
                } else if (payType == Payment.SKFS_JH) {
                    new JHAllPay(PayActivity.this, mTicket, mSelectedPmtId, currentPay, content).o2oConsume();
                }
            }
        });
        inputNumberDialogCommon.setIsCanInputPoint(false);
        inputNumberDialogCommon.setTitle("付款码");
        inputNumberDialogCommon.setContent("请输入付款码");
        inputNumberDialogCommon.setEtHint("请输入付款码");
        inputNumberDialogCommon.showDialog(false);

    }

    public void  payDialogMore(final List<Payment> payList){
        AlertDialog.Builder builder=new AlertDialog.Builder(PayActivity.this);
        final AlertDialog payDialog=builder.create();
        payDialog.setCancelable(true);
        View view =LayoutInflater.from(PayActivity.this).inflate(R.layout.dialog_more_pay,null);
        RelativeLayout rl_close=view.findViewById(R.id.rl_close);
        GridView gv_pay_more=view.findViewById(R.id.gv_pay_more);
        Button bt_item=view.findViewById(R.id.bt_item);
        final PayGridAdapter morePayAdapter=new PayGridAdapter(PayActivity.this,payList,false);
        gv_pay_more.setAdapter(morePayAdapter);
        gv_pay_more.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                payDialog.dismiss();
                mSelectPay = payList.get(position);
                mSelectedPmtId = payList.get(position).getPayCode();
                mSelectedPmtZlclfs = payList.get(position).getChangeType();
                payType = payList.get(position).getPayType();
                mPosition = position;
                morePayAdapter.setSelectPos(mPosition, true);
                payTypeSubmit();
            }
        });
        rl_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                payDialog.dismiss();
            }
        });
        bt_item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                payDialog.dismiss();
            }
        });
        payDialog.setView(view,0,0,0,0);
        payDialog.show();
        payDialog.getWindow().setBackgroundDrawableResource(R.drawable.dialog_bg_common);
    }

    /**
     *
     * @param payMoney 当前交易金额
     * @param clearFlag 是否为清空收款方式操作
     */
    public void reqAddPayAndCommitNet(int payMoney,boolean clearFlag){
//        if((payMoney + mTicket.getHasPayed()) >= mTicket.getTotalMoney()){
//            fastTradingProgress.show();
//            new CustomerPaymentPresenter(this, mSelectedPmtId, payType, payMoney).addCustomerPayment();
//        }else{
            reqAddpayNet(payMoney,clearFlag);
 //       }
    }

    /*
    请求同步付款
     */
    public void reqAddpayNet(int payMoney,boolean clearFlag){
        payItemList.clear();
        payItem.setPayAmount(MoneyUtils.getMoneyStr(payMoney));
        payItem.setPayCode(mSelectedPmtId);
        payItem.setPayType(payType);
        payItem.setChangeType(mSelectedPmtZlclfs);
        if(payItem.getDjdInfoList()!=null)
        payItem.getDjdInfoList().clear();
        if(mSelectedPmtId == Payment.SKFS_DJD){
            for(DepositUseData item :mTicket.getDepositUsedList()){
                DjdInfo data = new DjdInfo();
                data.setDjdh(item.getOrderNo());
                data.setPayAmount(item.getDepositAmt());
                payItem.getDjdInfoList().add(data);
            }
        }
        payItemList.add(payItem);
        netPresenter.saveAddpayRequest(mTicket.getOrderNo(), payItemList,saleType,clearFlag); // 同步付款 （确认支付调用）

    }







    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_act_pay_confirm:{
                if (needWait) {
                    ToastUtils.showMsg("正在交易请等待");
                    return;
                }
                if (Double.parseDouble(waitPayMoney)>0) {
                    ToastUtils.showMsg("没有支付足够的金额，不能完成交易");
                    break;
                }
                needWait = true;
                netPresenter.saveCommitPayRequest(mTicket,false);
            }
            break;
            default:
                break;
        }
    }

    /**
     * 顾客付款方式列表更新
     */
    @Override
    public void updateCustomerPaymentList() {
        PayUtil.sortTicketPayments(mTicket);//小票排序
        payListAdapter.updateData(mTicket.getPayList());
        //更新总的信息
        CalculatorPayed();
        if (ErpCommonData.isAutoSaveTicket.equals("0")){  //自动打印
            if (Double.parseDouble(waitPayMoney)<=0){  //实现自动保存交易 （在支付时，金额足够之后，可以自动打印小票)
                netPresenter.saveCommitPayRequest(mTicket,false);
            }
        }

        if(fastTradingProgress.isShowing())
            fastTradingProgress.dismiss();
    }
    private void CalculatorPayed() {
        tv_good_price.setText("￥"+new DecimalFormat("0.00").format(new BigDecimal(mTicket.getTotalAmount()+ "").add(new BigDecimal(mTicket.getTotalDiscount())).doubleValue()));
        tv_pay_money.setText("￥"+MoneyUtils.getMoneyStr(mTicket.getTotalMoney()));
        tv_discount_price.setText("￥"+new DecimalFormat("0.00").format(new BigDecimal(mTicket.getTotalDiscount() + "").add(new BigDecimal(mTicket.getDecPreferentialMoney())).doubleValue()));
        if(new BigDecimal(mTicket.getChangeAmount() + "").doubleValue()>0){
            tv_wait_pay_money.setText("￥0.00");
            tv_change_money.setText("￥"+new DecimalFormat("0.00").format(new BigDecimal(mTicket.getChangeAmount() + "").doubleValue()));
        }else {
            tv_wait_pay_money.setText("￥"+waitPayMoney);
            tv_change_money.setText("￥0.00");
        }
        tv_collect_money.setText("￥"+MoneyUtils.getMoneyStr(mTicket.getHasPayed()));
    }

    @Override
    public void showProgress(String msg) {
        mProgressDialog.setMessage(msg);
        mProgressDialog.show();
    }

    @Override
    public void dismissProgress() {
        mProgressDialog.dismiss();
    }

    /**
     * 网络请求失败
     * @param msg
     * @param requestHandId
     */
    @Override
    public void showLoadFailureMsg(String msg, int requestHandId) {
        ToastUtils.show(msg);
        needWait = false;
        isWxOrZfBBL = false;
        //如果是微信支付宝同步付款失败怎么处理？
        if(fastTradingProgress.isShowing())
            fastTradingProgress.dismiss();
    }
    /**
     * 同步付款失败
     * @param msg
     * @param payItems
     */
    @Override
    public void saveAddpayRequestFail(String msg, List<Payment> payItems) {
        if(fastTradingProgress.isShowing())
            fastTradingProgress.dismiss();
        bodyCodeErrorDialog("同步付款失败,"+msg,Constant.PAY_FUNCTION_NETRET_ADDPAY,null,payItems);
    }

    private void bodyCodeErrorDialog(String msg, final int handleId, final ConsumeCrmPayData payData,
                                     final List<Payment> payItems) {
        SaleUtil.showInfoDialog(PayActivity.this,
                ConstantString.DIALOG_MAIN_SUSPEND_ORDER_FAIL_TITLE,
                msg+"/n"+"是否重新发起请求？",
                new OnDialogListener() {
                    @Override
                    public void onClick(int flag) {
                        if(flag == DialogConstant.DIALOG_BTN_SURE){
                            if(handleId==Constant.PAY_FUNCTION_NETRET_CONSUME ){//consume失败
                                fastTradingProgress.show();
                                reqConsumeCrmPay();
                            }else if(handleId == Constant.PAY_FUNCTION_NETRET_ADDPAY && payItems!=null){//addPays失败
                                fastTradingProgress.show();
                                netPresenter.saveAddpayRequest(mTicket.getOrderNo(), payItems,saleType,false); // 同步付款 （确认支付调用）
                            }
                        }
                    }
                });

    }



    /**
     * 同步付款成功
     @param addpayRes
     */
    @Override
    public void saveAddpayRequestData(R_Addpay addpayRes) {
        mTicket.setTotalAmount(MoneyUtils.getMabMoneyString(addpayRes.getTotalAmount()));
        mTicket.setTotalDiscount(MoneyUtils.getMabMoneyString(addpayRes.getTotalDiscount()));
        mTicket.setDecMoney(MoneyUtils.getMabMoneyString(addpayRes.getDecMoney()));
        mTicket.setChangeAmount(MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(addpayRes.getChangeAmount())));
        waitPayMoney=new DecimalFormat("0.00").format(Math.abs(Double.parseDouble(addpayRes.getAmountPayable())));
        if(isDeletePayRequestAddpay){//删除收款方式同步
            isDeletePayRequestAddpay = false;
            Iterator<Payment> iterator = mTicket.getPayList().iterator();
            while (iterator.hasNext()) {
                Payment p = iterator.next();
                if(p.getPayCode() == currentDelPayCode){
                    if(p.getPayCode() ==9999){//卡券
                        mTicket.getCardCouponList().clear();
                    }else if(p.getPayCode() ==8888){//编码券
                        mTicket.getCodedCouponList().clear();
                    }else if(p.getPayCode() ==4){//储值卡
                        mTicket.getCashCardList().clear();
                    }
                    iterator.remove();
                }
            }
            updateCustomerPaymentList();
        }else if(clearAllPay){//付款界面按返回键请求同步付款成功
            cancelTrade();
            finish();
        }else{
            if(payType == Payment.SKFS_CZK){
                int totalPayMoney = 0;
                for (CashCardItem item : mTicket.getCashCardList()){
                    totalPayMoney += item.getmMoney();
                }
                Iterator<Payment> iterator = mTicket.getPayList().iterator();
                while (iterator.hasNext()) {
                    Payment p = iterator.next();
                    if(p.getPayCode() == mSelectedPmtId){
                        iterator.remove();
                    }
                }
                //生成付款方式
                Payment payment = PayUtil.createPayment(mSelectedPmtId);
                payment.setPayAmount(MoneyUtils.getMoneyStr(totalPayMoney));
                mTicket.getPayList().add(payment);
                updateCustomerPaymentList();
            }else if(payType==Payment.SKFS_YHQK){

//                int totalCouponPayMoney = 0;
//                if(mSelectPay.getIsCoded() ==1){
//                    for (CodeCoupon item : mTicket.getCodedCouponList()){
//                        totalCouponPayMoney += item.getUsedMoney();
//                    }
//                    //生成付款方式
//                    Payment payment = getCodedCouponPayment();
//                    payment.setPayAmount(MoneyUtils.getMoneyStr(Math.abs(totalCouponPayMoney)));
//                }else{
//                    for (CardCouponItem item : mTicket.getCardCouponList()){
//                        totalCouponPayMoney += item.getUsedMoney();
//                    }
//                    //生成付款方式
//                    Payment payment = getCardCouponPayment();
//                    payment.setPayAmount(MoneyUtils.getMoneyStr(Math.abs(totalCouponPayMoney)));
//                }
//                updateCustomerPaymentList();

                if (mTicket.getCodedCouponList().size()>0) {
                    int totalCouponPayMoney = 0;
                    for (CodeCoupon item : mTicket.getCodedCouponList()) {
                        totalCouponPayMoney += item.getUsedMoney();
                    }
                    //生成付款方式
                    Payment payment = getCodedCouponPayment();
                    payment.setPayAmount(MoneyUtils.getMoneyStr(Math.abs(totalCouponPayMoney)));
                    // Log.e("TAG","totalCouponPayMoney1=="+totalCouponPayMoney);
                }
                if( mTicket.getCardCouponList().size()>0) {
                    int totalCouponPayMoney = 0;
                    for (CardCouponItem item : mTicket.getCardCouponList()) {
                        totalCouponPayMoney += item.getUsedMoney();
                    }
                    //生成付款方式
                    Payment payment = getCardCouponPayment();
                    payment.setPayAmount(MoneyUtils.getMoneyStr(Math.abs(totalCouponPayMoney)));
                    // Log.e("TAG","totalCouponPayMoney2=="+totalCouponPayMoney);
                }
                updateCustomerPaymentList();

            }else if(payType==Payment.SKFS_DJD){//订金单
                int usedDepositM = 0;//订金单使用总金额
                for (DepositUseData data : mTicket.getDepositUsedList()) {
                    usedDepositM += MoneyUtils.getMoneyInt(data.getDepositAmt());
                }
                //生成付款方式
                Payment payment = getDjdPayment();
                payment.setPayAmount(MoneyUtils.getMoneyStr(Math.abs(usedDepositM)));
                updateCustomerPaymentList();

            }
            else{
                //生成收款方式
                new CustomerPaymentPresenter(this, mSelectedPmtId, payType, currentPay).addCustomerPayment();
            }
        }
        setAdPresentation(2);
    }

    private Payment getCodedCouponPayment() {
        if (mTicket == null)
            return null;
        Iterator<Payment> iterator = mTicket.getPayList().iterator();
        while (iterator.hasNext()) {
            Payment p = iterator.next();
            if(p.getPayCode() ==8888){
                iterator.remove();
            }
        }
        Payment payMent = new Payment(Payment.SKFS_YHQK);
        payMent.setPayCode(8888);
        payMent.setIsCoded(1);
        payMent.setPayName("编码券一体");
        mTicket.getPayList().add(payMent);
        return payMent;
    }

    private Payment getCardCouponPayment() {
        if (mTicket == null)
            return null;
        Iterator<Payment> iterator = mTicket.getPayList().iterator();
        while (iterator.hasNext()) {
            Payment p = iterator.next();
            if(p.getPayCode() ==9999){
                iterator.remove();
            }
        }
        Payment payMent = new Payment(Payment.SKFS_YHQK);
        payMent.setPayCode(9999);
        payMent.setPayName("电子卡券");
        mTicket.getPayList().add(payMent);
        return payMent;
    }

    private Payment getDjdPayment() {
        if (mTicket == null)
            return null;
        Iterator<Payment> iterator = mTicket.getPayList().iterator();
        while (iterator.hasNext()) {
            Payment p = iterator.next();
            if(p.getPayCode() ==Payment.SKFS_DJD){
                iterator.remove();
            }
        }
        Payment payMent = new Payment(Payment.SKFS_DJD);
        payMent.setPayCode(Payment.SKFS_DJD);
        payMent.setPayName("订金单");
        mTicket.getPayList().add(payMent);
        return payMent;
    }
    /**
     * 完成交易成功
     * @param backTicket
     * @param isCancelAfterSwipe 后刷卡取消标志   true 取消
     */

    @Override
    public void saveCommitPayRequestData(TicketInfo backTicket, boolean isCancelAfterSwipe) {
//        ErpCommonData.isFSTH=false;
//        ErpCommonData.isDJD=false;
        //需要返券会员且没有取消刷卡
        if(fastTradingProgress.isShowing())
            fastTradingProgress.dismiss();
        backTicket.setFSTH(mTicket.isFSTH());
        ComSharedPreferences.WriteSharedPreferences("JLBH","jlbh",backTicket.getJlbh());//脱机记录编号
        if (backTicket.isNeedVipToOfferCoupon() && !isCancelAfterSwipe){
            PayUtil.showQueryMemberDialog(PayActivity.this,Constant.MEMBER_IDENTIFYING_DELIVERYCOUPON);
        }else if(backTicket.isNeedBuyCent() && saleType ==1){//需要买分且退货
            ToastUtils.show("积分不足,不能退货！");
        }else {
            if(backTicket.getOfferCouponList()!=null && backTicket.getOfferCouponList().size()>0){//有返券
                ArrayList<Coupon> list = new ArrayList<>();
                for (OfferCoupon item : backTicket.getOfferCouponList()) {
                    if (mTicket.getOfferCouponVipCode() != null && !"null".equals(mTicket.getOfferCouponVipCode())) {
                        item.setOfferMemberCardNo(mTicket.getOfferCouponVipCode());
                        item.setOfferMemberCardId(mTicket.getOfferCouponVipId());
                    } else {
                        if (mTicket.getMemberInfo() != null) {
                            item.setOfferMemberCardNo(mTicket.getMemberInfo().getMemberCardNo());
                            item.setOfferMemberCardId(mTicket.getMemberInfo().getMemberCardId());
                        }
                    }

                    if(item.getCouponType()==6||item.getCouponTypeName().startsWith("编码券")||item.getCodeCoupons()!=null&&item.getCodeCoupons().size()>0){
                        if(item.getCodeCoupons()!=null&&item.getCodeCoupons().size()>0){
                            for(int i=0;i<item.getCodeCoupons().size();i++){
                                Coupon coupon = new Coupon();
                                coupon.setCouponTypeName(item.getCodeCoupons().get(i).getCodeCouponName());
                                coupon.setAvailableAmount(item.getCodeCoupons().get(i).getBalance() + "");
                                coupon.setValidDate(item.getCodeCoupons().get(i).getDateValid());
                                coupon.setCouponCode(item.getCodeCoupons().get(i).getCouponCode());
                                list.add(coupon);
                            }
                        }
                    }else {
                        if (mTicket.getOfferCouponVipCode() != null && !"null".equals(mTicket.getOfferCouponVipCode())) {
                            Coupon coupon = new Coupon();
                            coupon.setCouponTypeName(item.getCouponTypeName());
                            coupon.setAvailableAmount(item.getOfferMoney() + "");
                            coupon.setValidDate(item.getValidDate());
                            coupon.setCouponCode("");
                            list.add(coupon);
                        } else {
                            if (mTicket.getMemberInfo() != null) {
                                Coupon coupon = new Coupon();
                                coupon.setCouponTypeName(item.getCouponTypeName());
                                coupon.setAvailableAmount(item.getOfferMoney() + "");
                                coupon.setValidDate(item.getValidDate());
                                coupon.setCouponCode("");
                                list.add(coupon);
                            }
                        }

                    }
                }
                if (list.size() > 0) {
                    showBackCouponDialog(backTicket, list);
                }
            }else{
                //打印小票
                ToastUtils.show("交易成功！");
                printerTraceTicket(backTicket);
            }
        }
    }

    /**
     * 返券信息dialog
     * @param backTicket
     * @param list
     */
    public void showBackCouponDialog(final TicketInfo backTicket, ArrayList<Coupon> list) {
        CouponMessageDialogCommon couponMessageDialogCommon=CouponMessageDialogCommon.getCouponMessageDialogCommon(PayActivity.this, list, new ArrayList<Coupon>(), new CouponMessageDialogCommon.CouponMessageDialogCommonOnClickListener() {
            @Override
            public void couponMessageDialogCommonOnClick() {
                printerTraceTicket(backTicket);
            }
        });
        couponMessageDialogCommon.setTitle("本次发放");
        couponMessageDialogCommon.setTitleOne("返券信息");
        couponMessageDialogCommon.setTitleTwoGone(true);
        couponMessageDialogCommon.setListTwoeGone(true);
        couponMessageDialogCommon.setIv_close(true);
        couponMessageDialogCommon.setBt_cancle(true);
        couponMessageDialogCommon.showDialog(false);
    }


    private void printerTraceTicket(TicketInfo backTicket) {
        if (backTicket != null) {
            //将小票交易号保存到本地
            SharedPreferences pref = getSharedPreferences("TradeNo", 0);
            SharedPreferences.Editor prefEdit = pref.edit();
            prefEdit.putString("TicketOrderNo", backTicket.getOrderNo());
            prefEdit.commit();
            SDTools.writeTicket(backTicket);
            if(ErpCommonData.isPrint){
                showPrintDialog(backTicket);
            }else {
                print(backTicket);
            }

        }
    }

    /**
     * 返券后刷卡查会员成功
     * @param member
     */
    @Override
    public void saveGetVipCardToGrantVoucher(Member member) {
        mTicket.setOfferCouponVipCode(member.getMemberCardNo());
        mTicket.setOfferCouponVipId(member.getMemberCardId());
        netPresenter.saveCommitPayRequest(mTicket,false);
    }

    /**
     * 刷卡返回
     *
     */
    @Override
    public void doAfterSwipeCard(boolean isSuccess, String content, int handId) {
        switch (handId) {
            case Constant.PAY_AFTER_SWIPECARD_HANDLEID:{
                if(isSuccess) {
                    if (!content.equals("")) {
                        QueryMemberRequest requestParam = new QueryMemberRequest();
                        requestParam.setServerBillId(Integer.parseInt(mTicket.getServerBillId()));
                        requestParam.setCondType(SktConfigIdCrmConstant.SKT_CONFIG_MEMBER_TYPE_SWIPE);
                        requestParam.setCondValue(content);
                        requestParam.setSktno(ErpCommonData.sktno);
                        netPresenter.getVipCardToGrantVoucher(requestParam);
                    }else{
                        ToastUtils.showMsg("刷卡失败，请重试！");
                    }
                }
                else{
                    if(content.contains("取消") && vipCardToGrantCount <2){//防止客户误点刷卡取消按钮
//                        showQueryMemberDialog(1);
                        PayUtil.showQueryMemberDialog(PayActivity.this,Constant.MEMBER_IDENTIFYING_DELIVERYCOUPON);
                        vipCardToGrantCount++;
                    }else{
                        netPresenter.saveCommitPayRequest(mTicket,true);
                        ToastUtils.show( "取消刷卡");
                    }
                }
            }
            break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case BankFunctionConstant.THIRD_APP_BANK_TRADE:{//第三银行
                R_BankData r_data = new R_BankData();
                new BOC_BeiJing_Function().handleBankData(r_data,data);
                reqBankTradeConsume(r_data);//后期逻辑处理
            }
            break;
            case Constant.PAY_JUMP_YHQK_HANDLEID: {//优惠卡券
                payAdapter.setSelectPos(mPosition, false);
                if(mTicket.getCardCouponList().size()>0){
                    if(!GetConfigs.isTradeCutPayment()){//结账时扣款
                        cardCouponHandleData(0);
                    }else{//立即扣款
                        updateCustomerPaymentList();
                    }
                }
            }
            break;
            case Constant.CZK_COMPLETED_ID:{//储值卡
                payAdapter.setSelectPos(mPosition, false);
                if(mTicket.getCashCardList().size()>0){
                    if(!GetConfigs.isTradeCutPayment()){//结账时扣款
                        cashCardHandleData();
                    }else{//立即扣款
                        updateCustomerPaymentList();
                    }
                }
            }
            break;
            case Constant.PAY_CODED_COUPON_REQUEST_CODE: {//编码券
                payAdapter.setSelectPos(mPosition, false);
                if(mTicket.getCodedCouponList().size()>0){
                    if(!GetConfigs.isTradeCutPayment()){//结账时扣款
                        codedCouponHandleData(0);
                    }else{//立即扣款
                        updateCustomerPaymentList();
                    }
                }
            }
            break;
            case Constant.PAY_ZFB_SCANCODE_RESULTID:{//支付宝扫码
                if(data==null){
                    return;
                }
                String content = data.getStringExtra("Code");
                if ("".equals(content)) {
                    Toast.makeText(this, "扫码结果为空", Toast.LENGTH_LONG).show();
                    return;
                }
                String codeNumber=content.substring(0,2);
                if(isInteger(codeNumber)) {
                    if (Integer.parseInt(codeNumber) < 25) {
                        Toast.makeText(this, "请扫码支付宝付款码!", Toast.LENGTH_LONG).show();
                        return;
                    }
                }else{
                    Toast.makeText(this, "请扫码支付宝付款码!", Toast.LENGTH_LONG).show();
                    return;
                }
                MessageLog.writeLog("ZFB扫码结果为：" + content);
                new Alipay(PayActivity.this, mTicket, mSelectedPmtId, currentPay, content).o2oConsume();
            }
            break;
            case Constant.PAY_WX_SCANCODE_RESULTID:{//微信扫码
                if(data==null){
                    return;
                }
                String content = data.getStringExtra("Code");
                if ("".equals(content)) {
                    Toast.makeText(this, "扫码结果为空", Toast.LENGTH_LONG).show();
                    return;
                }
                String codeNumber=content.substring(0,2);
                if(isInteger(codeNumber)) {
                    if (Integer.parseInt(codeNumber) >= 25) {
                        Toast.makeText(this, "请扫码微信付款码!", Toast.LENGTH_LONG).show();
                        return;
                    }
                }else{
                    Toast.makeText(this, "请扫码微信付款码!", Toast.LENGTH_LONG).show();
                    return;
                }
                MessageLog.writeLog("WX扫码结果为：" + content+" ");
                LogUtils.d("PayActivity","微信当前收款方式的id为："+mSelectedPmtId);
                new WechatPay(PayActivity.this, mTicket, mSelectedPmtId, currentPay, content).o2oConsume();

            }
            break;
            case Constant.PAY_JH_SCANCODE_RESULTID:{//聚合扫码
                if(data==null){
                    return;
                }
                String content = data.getStringExtra("Code");
                if ("".equals(content)) {
                    Toast.makeText(this, "扫码结果为空", Toast.LENGTH_LONG).show();
                    return;
                }
                MessageLog.writeLog("扫码结果为：" + content);
                new JHAllPay(PayActivity.this, mTicket, mSelectedPmtId, currentPay, content).o2oConsume();

            }
            break;
            case Constant.PAY_ZFB_SCANCODE_FSREFUNDRESULTID:{//支付宝扫码
                if(data==null){
                    return;
                }
                String content = data.getStringExtra("Code");
                if ("".equals(content)) {
                    Toast.makeText(this, "扫码结果为空", Toast.LENGTH_LONG).show();
                    return;
                }

                MessageLog.writeLog("ZFB负数退货扫码结果为：" + content);
                new Alipay(PayActivity.this, mTicket, mSelectedPmtId, currentPay, content).o2oConsume();
            }
            break;
            case Constant.PAY_WX_SCANCODE_FSREFUNDRESULTID:{//微信扫码
                if(data==null){
                    return;
                }
                String content = data.getStringExtra("Code");
                if ("".equals(content)) {
                    Toast.makeText(this, "扫码结果为空", Toast.LENGTH_LONG).show();
                    return;
                }
                MessageLog.writeLog("WX负数退货扫码结果为：" + content+" ");
                LogUtils.d("PayActivity","微信当前收款方式的id为："+mSelectedPmtId);
                new WechatPay(PayActivity.this, mTicket, mSelectedPmtId, currentPay, content).o2oConsume();

            }
            break;
            case Constant.PAY_JH_SCANCODE_FSREFUNDRESULTID:{//聚合负数退货扫码
                if(data==null){
                    return;
                }
                String content = data.getStringExtra("Code");
                if ("".equals(content)) {
                    Toast.makeText(this, "扫码结果为空", Toast.LENGTH_LONG).show();
                    return;
                }
                MessageLog.writeLog("聚合负数退货扫码结果为：" + content+" ");
                LogUtils.d("PayActivity","聚合当前收款方式的id为："+mSelectedPmtId);
                new JHAllPay(PayActivity.this, mTicket, mSelectedPmtId, currentPay, content).o2oConsume();

            }
            break;
            case Constant.PAY_AFTER_SCAN_HANDLEID:{//后返券扫码
                if(data==null){
                    return;
                }
                String content = data.getStringExtra("Code");
                if ("".equals(content)) {
                    ToastUtils.showMsg("扫码结果为空");
                }else{
                    QueryMemberRequest requestParam = new QueryMemberRequest();
                    requestParam.setServerBillId(Integer.parseInt(mTicket.getServerBillId()));
                    requestParam.setCondType(SktConfigIdCrmConstant.SKT_CONFIG_MEMBER_TYPE_SCAN);
                    requestParam.setCondValue(content);
                    requestParam.setSktno(ErpCommonData.sktno);
                    netPresenter.getVipCardToGrantVoucher(requestParam);
                }
            }
            break;
            case Constant.PAY_DJD_SCANCODE_RESULTID:{//订金单扫码结果
                if(data==null){
                    return;
                }
                String content = data.getStringExtra("Code");
                if ("".equals(content)) {
                    ToastUtils.showMsg("扫码结果为空");
                }else{
                    netPresenter.queryDepositInfo(content);
                }
            }

            case Constant.PAY_ICBC_TRADS_RESULTID_BACK:{//银行卡退货
                YhkCardItem yhkCardItem = BankpayManger.getInstance().onActivityResultBack(data, mSelectedPmtId, payType,false);
                reqBankTradeConsume(yhkCardItem);
            }
            break;
            case Constant.PAY_ICBC_TRADS_RESULTID:{//银行卡支付
                YhkCardItem yhkCardItem  =BankpayManger.getInstance().onActivityResultBack(data ,mSelectedPmtId,payType,true);
                reqBankTradeConsume(yhkCardItem);
            }
            break;
            case Constant.PAY_O2O_BL_SCANCODE_RESULTID:{//微信支付宝扫码补录
                if(data==null){
                    return;
                }
                String content = data.getStringExtra("Code");
                if ("".equals(content)) {
                    ToastUtils.showMsg("扫码结果为空");
                }else{
                    if(payType == Payment.SKFS_WX ){//微信
                        MessageLog.writeLog("WX补录扫码结果为：" + content);
                        new WechatPay(PayActivity.this,mTicket,mSelectedPmtId,0,content).o2oBl();
                    }else if(payType == Payment.SKFS_ZFB){//支付宝
                        MessageLog.writeLog("ZFB补录扫码结果为：" + content);
                        new Alipay(PayActivity.this,mTicket,mSelectedPmtId,0,content).o2oBl();
                    }

                }
            }
            break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void reqBankTradeConsume(R_BankData r_data) {
        if(r_data.getResCode().equals("0")){
            YhkCardItem  xykItem = new YhkCardItem();
            xykItem.setAmount(r_data.getAmt());
            xykItem.setLsh(r_data.getTraceNo());
            xykItem.setPzh(r_data.getBatchNo());
            xykItem.setCkh(r_data.getRefNo());
            xykItem.setCardNo(r_data.getCardNo());
            xykItem.setYhje("0");
            xykItem.setYhje_shop("0");
            xykItem.setSkfs(mSelectedPmtId+"");
            xykItem.setType(payType+"");
            if(isWxOrZfBBL){
                if (saleType == 1) {
                    xykItem.setSaleType(4);
                } else {
                    xykItem.setSaleType(3);
                }
            }else {
                if (saleType == 1) {
                    xykItem.setSaleType(1);
                } else {
                    xykItem.setSaleType(0);
                }
            }
            yhkCardList.add(xykItem);
            reqConsumeCrmPay();
        }else{
            ToastUtils.showMsg("第三方交易处理异常！");
        }
    }

    private void reqConsumeCrmPay() {
        ConsumeCrmPayData payData=new ConsumeCrmPayData();
        payData.setOrderno(mTicket.getOrderNo());
        payData.setCode(mSelectedPmtId +"");
        payData.setType(1);
        payData.setGuid(UUID.randomUUID().toString());
        payData.setYhkCard(yhkCardList);
        PosHttpManager.ConsumeCrmPay(payData, new OkHttpUtils.ResultCallback() {
            @Override
            public void onSuccess(JsonObject response) {
                if(fastTradingProgress.isShowing())
                    fastTradingProgress.dismiss();
                BaseResponse<BaseResponse> baseResponse = BaseResponse.fromJson(response.toString(), BaseResponse.class);
                if(baseResponse.getCode().equals("0")) {
                    ToastUtils.show("明细保存成功!");
                    int money=0;
                    for(int i=0;i<yhkCardList.size();i++){
                        if(yhkCardList.get(i).getSkfs().equals(mSelectedPmtId+"")){
                            money=money+MoneyUtils.getMoneyInt(yhkCardList.get(i).getAmount());
                        }
                    }
                    currentPay=money;
                    reqAddpayNet(money, false);
                }else{
                    if (TextUtils.isEmpty(baseResponse.getTips())){
                        bodyCodeErrorDialog("明细保存失败,"+baseResponse.getMsg(),Constant.PAY_FUNCTION_NETRET_CONSUME,null,null);
                    }else {
                        bodyCodeErrorDialog("明细保存失败,"+baseResponse.getTips(),Constant.PAY_FUNCTION_NETRET_CONSUME,null,null);
                    }
                }

            }

            @Override
            public void onFailure(String msg) {
                if(fastTradingProgress.isShowing())
                    fastTradingProgress.dismiss();
                bodyCodeErrorDialog("明细保存失败,"+msg,Constant.PAY_FUNCTION_NETRET_CONSUME,null,null);
            }
        });
    }


    private void reqBankTradeConsume(YhkCardItem xykItem) {
        ErpCommonData.ticketInfo.getBankCardList().add(xykItem);
        ConsumeCrmPayData payData=new ConsumeCrmPayData();
        payData.setOrderno(ErpCommonData.ticketInfo.getOrderNo());
        payData.setCode(mSelectedPmtId +"");
        payData.setType(1);
        payData.setSaleType(0);
        payData.setStoreCode(ErpCommonData.storeCode);
        payData.setGuid(UUID.randomUUID().toString());
        payData.getYhkCard().add(xykItem);

        PosHttpManager.ConsumeCrmPay(payData, new OkHttpUtils.ResultCallback() {
            @Override
            public void onSuccess(JsonObject response) {
                Log.e("TAG","response=="+response.toString());
                String code = response.get("Code").getAsString();
                String msg = "";
                if (!response.get("Msg").isJsonNull()){
                    msg = response.get("Msg").getAsString();
                }
                if(code.equals("0")){
                    ToastUtils.showMsg("银行扣款成功！");
                    int totalMoney = 0;
                    for (YhkCardItem item : ErpCommonData.ticketInfo.getBankCardList()){
                        totalMoney += MoneyUtils.getMoneyInt(item.getAmount());
                    }
                    //生成付款方式
                    Payment payment =  PayUtil.createPayment(mSelectedPmtId);
                    payment.setPayAmount(MoneyUtils.getMoneyStr(totalMoney));
                    mTicket.getPayList().add(payment);
                    updateCustomerPaymentList();
                }else{
                    ToastUtils.showMsg( "银行扣款成功保存失败，"+msg);
                }
            }

            @Override
            public void onFailure(String msg) {
                ToastUtils.showMsg( "银行扣款成功保存失败,"+msg);
            }
        });
    }

    /**
     * 编码券处理数据
     * deleFlag 0  消费同步付款    1删除收款方式同步付款
     */
    private void codedCouponHandleData(int deleFlag) {
        //1.调用同步付款接口
        List<Integer> couponTypeList = new ArrayList<>();//类型列表（有重复的）
        List<Integer> differenceCouponTypeList = new ArrayList<>();//不同的券类型列表
        for(CodeCoupon coded :mTicket.getCodedCouponList()){
            couponTypeList.add(coded.getCouponType());
        }
        for(Integer type: couponTypeList){
            if(differenceCouponTypeList.size()>0){
                boolean isExistSame = false;
                for(Integer difType: differenceCouponTypeList){
                    if(type == difType){
                        isExistSame = true;
                        break;
                    }
                }
                if(!isExistSame){
                    differenceCouponTypeList.add(type);
                }
            }else{
                differenceCouponTypeList.add(type);
            }
        }

        payItemList.clear();
        LogUtils.e("PayActivity","payItemList长度："+payItemList.size());
        for(Integer difType: differenceCouponTypeList){
            Payment payI = new Payment();
            int totalMoneyDifTypeCoupon =0 ;
            for(CodeCoupon usedCoupon :mTicket.getCodedCouponList()){
                if(usedCoupon.getCouponType() == difType){
                    totalMoneyDifTypeCoupon += usedCoupon.getUsedMoney();
                }
            }
            for(Payment p :ErpCommonData.loadConfig.getPayList()){
                if(p.getYhqId() == difType){
                    payI.setPayCode(p.getPayCode());
                    LogUtils.e("PayActivity","编码券付款的PAYCODE："+payI.getPayCode());
                    break;
                }
            }
            if(deleFlag ==1){
                payI.setPayAmount(MoneyUtils.getMoneyStr(0));
            }else{
                payI.setPayAmount(MoneyUtils.getMoneyStr(totalMoneyDifTypeCoupon));
            }
            payI.setPayAmount(MoneyUtils.getMoneyStr(totalMoneyDifTypeCoupon));
            payI.setPayType(Payment.SKFS_YHQK);
            payI.setIsCoded(1);
            payItemList.add(payI);
        }
        netPresenter.saveAddpayRequest(mTicket.getOrderNo(),
                payItemList,
                saleType,false);

    }

    /**
     * 储值卡处理数据
     */
    private void cashCardHandleData() {
        payAdapter.setSelectPos(mPosition, false);
        int money=0;
        for (CashCardItem item :mTicket.getCashCardList()){
            money +=item.getmMoney();
        }
        payItemList.clear();
        payItem.setPayAmount(MoneyUtils.getMoneyStr(money));
        payItem.setPayCode(mSelectedPmtId);
        payItem.setPayType(payType);
        payItemList.add(payItem);
        netPresenter.saveAddpayRequest(mTicket.getOrderNo(), payItemList,saleType,false);
    }

    /**
     * 卡券处理数据
     * deleFlag 0  消费同步付款    1删除收款方式同步付款
     */
    private void cardCouponHandleData(int deleFlag) {
        List<Integer> couponTypeList = new ArrayList<>();//类型列表（有重复的）
        List<Integer> differenceCouponTypeList = new ArrayList<>();//不同的券类型列表
        MessageLog.writeLog("当前小票卡券列表长度为："+mTicket.getCardCouponList().size());
        for(CardCouponItem usedCoupon : mTicket.getCardCouponList()){
            couponTypeList.add(usedCoupon.getCouponType());
        }
        for(Integer type: couponTypeList){
            if(differenceCouponTypeList.size()>0){
                boolean isExistSame = false;
                for(Integer difType: differenceCouponTypeList){
                    if(type == difType){
                        isExistSame = true;
                        break;
                    }
                }
                if(!isExistSame){
                    differenceCouponTypeList.add(type);
                }
            }else{
                differenceCouponTypeList.add(type);
            }
        }

        payItemList.clear();
        MessageLog.writeLog("payItemList长度："+payItemList.size());
        for(Integer difType: differenceCouponTypeList){//
            Payment payI = new Payment();
            int totalMoneyDifTypeCoupon =0 ;
            for(CardCouponItem usedCoupon : mTicket.getCardCouponList()){
                if(usedCoupon.getCouponType() == difType){
                    totalMoneyDifTypeCoupon += usedCoupon.getUsedMoney();
                }
            }
            MessageLog.writeLog("当前券类型为difType：" + difType+"  当前券的使用金额totalMoneyDifTypeCoupon："+totalMoneyDifTypeCoupon);
            for(Payment p :ErpCommonData.loadConfig.getPayList()){
                if(p.getYhqId() == difType){
                    payI.setPayCode(p.getPayCode());
                    MessageLog.writeLog("当前券子列表的收款方式code为：" + p.getPayCode()+" 优惠券id为："+p.getYhqId());
                    break;
                }
            }
            if(deleFlag ==1){
                payI.setPayAmount(MoneyUtils.getMoneyStr(0));
            }else{
                payI.setPayAmount(MoneyUtils.getMoneyStr(totalMoneyDifTypeCoupon));
            }
            payI.setIsCoded(0);
            payI.setPayType(Payment.SKFS_YHQK);
            payItemList.add(payI);
        }
        MessageLog.writeLog("当前券子列表的长度为：" + payItemList.size());
        //1.调用振伟同步付款接口
        netPresenter.saveAddpayRequest(mTicket.getOrderNo(),
                payItemList,
                saleType,false);
    }
    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    public void payTypeSubmit(){
        switch (payType) {
            case Payment.SKFS_NORMAL:
                payDialogCommon();//测试通过
                LogUtils.i("Tag", "点击的按钮为--现金");
                break;
            case Payment.SKFS_YHQ:
                payDialogCommon();
                LogUtils.i("Tag", "点击的按钮为--纸券");
                break;
            case Payment.SKFS_WX:
                LogUtils.i("Tag", "点击的按钮为--微信");
                showO2OTraceType();
                break;
            case Payment.SKFS_ZFB:
                LogUtils.i("Tag", "点击的按钮为--支付宝");
                showO2OTraceType();
                break;
            case Payment.SKFS_JH:
                showO2OTraceType();
                break;
            case Payment.SKFS_YHK:
                payDialogCommon();
                LogUtils.i("Tag", "点击的按钮为--银行卡");
                break;
            case Payment.SKFS_CZK:
                LogUtils.i("Tag", "点击的按钮为--储值卡");
                handleCZKTrade();
                break;
            case Payment.SKFS_YHQK:
                if(mSelectPay.getIsCoded() ==1){//编码券
                    Intent codeIntent = new Intent(PayActivity.this, CodedCouponActivity.class);
                    codeIntent.putExtra("SelectedId", mSelectedPmtId);//付款方式ID
                    codeIntent.putExtra("PayType", payType);//付款方式type
                    startActivityForResult(codeIntent ,Constant.PAY_CODED_COUPON_REQUEST_CODE);//编码券
                }else{//优惠券
                    if (saleType == 1)
                        return;
                    Intent yhq = new Intent(PayActivity.this, CardCouponPayActivity.class);
                    yhq.putExtra("SelectedId", mSelectedPmtId);//付款方式ID
                    yhq.putExtra("PayType", payType);//付款方式type
                    yhq.setClass(PayActivity.this, CardCouponPayActivity.class);
                    startActivityForResult(yhq, Constant.PAY_JUMP_YHQK_HANDLEID);//优惠券
                }
                break;
            case Payment.SKFS_DJD:{//订金单
                showDepositUseDialog();
            }

            default:
                ToastUtils.show("暂不支持此收款方式!");
                break;
        }
    }

    /**
     * 副显数据
     * @param type
     */
    public void setAdPresentation(int type){
        switch (type) {
            case 1:
                adPresentationUtil=new AdPresentationUtil();
                if(adPresentationUtil!=null) {
                    adPresentationUtil.initDisplayData(this);
                    adPresentationUtil.setMode(1);
                    adPresentationUtil.setData(mTicket);
                }
                break;
            case 2:
                if(adPresentationUtil!=null) {
                    adPresentationUtil.setCalculatorPayed(mTicket);
                    adPresentationUtil.setPayment(mTicket.getPayList());
                }
                break;
            case 3:
                tv_change_money.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if(adPresentationUtil!=null) {
                            adPresentationUtil.dismiss();
                        }
                    }
                },1000);
                break;
        }

        }

    //订金单使用列表
    private void showDepositUseDialog() {
        View view = LayoutInflater.from(PayActivity.this).inflate(R.layout.view_function_deposituse, null);
        ((TextView) view.findViewById(R.id.tv_dialog_title_name)).setText("订金使用列表");
        final ListView lvDeposits = view.findViewById(R.id.lv_deposits_use);
        depositUseAdapter = new DepositUseAdapter(depositList,PayActivity.this);
        lvDeposits.setAdapter(depositUseAdapter);
        depositUseAdapter.notifyDataSetChanged();
        view.findViewById(R.id.tv_dialog_title_name).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });//取消
        view.findViewById(R.id.btn_cancel_input).setOnClickListener(new View.OnClickListener() {//生成订金单
            @Override
            public void onClick(View v) {//订金单添加
                int usedDepositM = 0;//订金单使用总金额
                for (DepositUseData data : depositList) {
                    usedDepositM += MoneyUtils.getMoneyInt(data.getDepositAmt());
                }
                int canPay = MoneyUtils.getMoneyInt(waitPayMoney);
                if (canPay <= usedDepositM) {
                    ToastUtils.showMsg("付款金额已足够！");
                }else{
                    showDepositQueryDialog();
                }
            }
        });
        view.findViewById(R.id.btn_djd_saoma).setOnClickListener(new View.OnClickListener() {//扫码
            @Override
            public void onClick(View v) {
                int usedDepositM = 0;//订金单使用总金额
                for (DepositUseData data : depositList) {
                    usedDepositM += MoneyUtils.getMoneyInt(data.getDepositAmt());
                }
                int canPay =MoneyUtils.getMoneyInt(waitPayMoney);
                if (canPay <= usedDepositM) {
                    ToastUtils.showMsg("付款金额已足够！");
                }else{
                      //订金单扫码
                }
            }
        });
        view.findViewById(R.id.btn_sure_input).setOnClickListener(new View.OnClickListener() {//完成
            @Override
            public void onClick(View v) {//订金单使用完成生成收款方式
                mDialog.dismiss();
                processDepositUsedData();
            }
        });
        AlertDialog.Builder dialog = new AlertDialog.Builder(PayActivity.this);
        dialog.setView(view).create();//.setCancelable(false)
        mDialog = dialog.show();
        WindowManager manager = getWindowManager();
        Display display = manager.getDefaultDisplay();
        int width = display.getWidth();
        int height = display.getHeight();
        mDialog.getWindow().setGravity(Gravity.CENTER);
        mDialog.getWindow().setLayout(width, height * 2 / 3);
    }

    /**
     * 生成订金单的收款方式
     */
    private void processDepositUsedData() {
        mTicket.getDepositUsedList().clear();
        mTicket.getDepositUsedList().addAll(depositList);
        int usedDepositM = 0;//订金单使用总金额
        for (DepositUseData data : depositList) {
            usedDepositM += MoneyUtils.getMoneyInt(data.getDepositAmt());
        }
        reqAddpayNet(usedDepositM,false);
        payAdapter.setSelectPos(mPosition, false);
    }

    /**
     * 查询订金单号详情
     */
    private void showDepositQueryDialog() {
        InputNumberDialogCommon inputNumberDialogCommon= InputNumberDialogCommon.getInputNumberDialogCommon(PayActivity.this, new InputNumberDialogCommon.InputDialogOnSubmitClickListener() {
            @Override
            public void InputDialogOnSubmitClick(String content) {
                if(content.equals("") || content==null){
                    ToastUtils.showMsg( "请输入订金单号");
                    return;
                }
                netPresenter.queryDepositInfo(content);
            }
        });
        inputNumberDialogCommon.setIsCanInputPoint(false);
        inputNumberDialogCommon.setTitle("输入订金单号");
        inputNumberDialogCommon.setContent("请输入订金单号");
        inputNumberDialogCommon.setEtHint("请输入订金单号");
        inputNumberDialogCommon.showDialog(false);

    }
    /**
     * 订金单查询成功
     * @param depositInfo
     */
    @Override
    public void queryDepositInfoDataSuccess(RefundOrder depositInfo) {
        DepositUseData item = new DepositUseData();
        Order order = depositInfo.getOrderList().get(0);
        item.setDepositAmt(order.getTotalAmount());
        item.setOrderNo(order.getOrderNo());
        item.setDepositInx(depositList.size()+1);
        boolean isDepositExist = false;
        int usedDepositM = 0;//订金单使用总金额
        for(DepositUseData usedItem :depositList){
            if(usedItem.getOrderNo().equals(item.getOrderNo())){
                isDepositExist = true;
                break;
            }
        }
        for(DepositUseData usedItem :depositList){
            usedDepositM += MoneyUtils.getMoneyInt(usedItem.getDepositAmt());
        }
        if(!isDepositExist){
            if(usedDepositM + MoneyUtils.getMoneyInt(item.getDepositAmt()) >  mTicket.getTotalMoney()){
                ToastUtils.showMsg("使用订金单总金额不能大于订单金额！");
            }else{
                depositList.add(item);
            }
        }
        else
            ToastUtils.showMsg("当前订金单已经存在,不能重复添加！");
        depositUseAdapter.notifyDataSetChanged();
    }

    public void paySubmit(String price){
        try{
            if(CommonUtils.isNumber(price)) {
                currentPay = MoneyUtils.getMoneyInt(price);
            }else{
                ToastUtils.show("请正确输入金额");
                return;
            }
        }catch (Exception e){
            ToastUtils.show("请正确输入金额");
            return;
        }
        Boolean checkFlag = PayUtil.payParamCheck(mSelectedPmtId,payType,currentPay,saleType,mTicket.getTotalMoney());
        if(!checkFlag){
            return ;
        }
        payAdapter.setSelectPos(mPosition, false);
        Payment payMent = PayUtil.createPayment(mSelectedPmtId);
        int result = payMent.PayProc(mTicket.getHasPayed(),currentPay,mTicket.getTotalMoney());
        if(result > 0){
            if(result ==1){
                ToastUtils.showMsg("找零不能超过一百元!",1);
            }else if(result ==2){
                ToastUtils.showMsg("本收款方式不能多收!",1);
            }
            return;
        }else {
            if(isWxOrZfBBL){
                PayUtil.paymentTypeHandle(payType, currentPay, PayActivity.this);
            }else {
                if (payType == Payment.SKFS_ZFB) {
                    if(mTicket.isFSTH()){
                        Intent intent = new Intent(PayActivity.this, ScanCodeActivity.class);
                        startActivityForResult(intent, Constant.PAY_ZFB_SCANCODE_FSREFUNDRESULTID);
                    }else {
                        Intent intent = new Intent(PayActivity.this, ScanCodeActivity.class);
                        startActivityForResult(intent, Constant.PAY_ZFB_SCANCODE_RESULTID);
                    }
                } else if (payType == Payment.SKFS_WX) {
                    if(mTicket.isFSTH()){
                        Intent intent = new Intent(PayActivity.this, ScanCodeActivity.class);
                        startActivityForResult(intent, Constant.PAY_WX_SCANCODE_FSREFUNDRESULTID);
                    }else {
                        Intent intent = new Intent(PayActivity.this, ScanCodeActivity.class);
                        startActivityForResult(intent, Constant.PAY_WX_SCANCODE_RESULTID);
                    }
                }  else if (payType == Payment.SKFS_JH) {
                    if(mTicket.isFSTH()){
                        Intent intent = new Intent(PayActivity.this, ScanCodeActivity.class);
                        startActivityForResult(intent, Constant.PAY_JH_SCANCODE_FSREFUNDRESULTID);
                    }else{
                        Intent intent = new Intent(PayActivity.this, ScanCodeActivity.class);
                        startActivityForResult(intent, Constant.PAY_JH_SCANCODE_RESULTID);
                    }
                }  else {
                    PayUtil.paymentTypeHandle(payType, currentPay, PayActivity.this);
                }
            }
        }
    }

    private void showCouponsBackDialog() {
        String titleMsg ="温馨提示";
        String messageMsg = "原交易有该收款台没有定义扣返券款的收款方式！";
        SaleUtil.showInfoDialog(PayActivity.this, titleMsg, messageMsg, new OnDialogListener() {
            @Override
            public void onClick(int flag) {
                finish();
            }
        });
    }

    public void print(TicketInfo backTicket){
        for(int i = 0; i<GetConfigs.ticketPrintCount(); i++){
            if (i==0){
                List<String> list = TicketFormat.createTicketFormat(backTicket,false,i);
                PrintManagerLib.initPrinter(PayActivity.this, CommonUtils.getSystemModel())
                        .initDevice()
                        .printList(list);
            }else if (i==1){
                List<String> list = TicketFormat.createTicketFormat(backTicket,false,i);
                PrintManagerLib.initPrinter(PayActivity.this,CommonUtils.getSystemModel())
                        .initDevice()
                        .printList(list);

            }else {
                List<String> list = TicketFormat.createTicketFormat(backTicket,false,-1);
                PrintManagerLib.initPrinter(PayActivity.this,CommonUtils.getSystemModel())
                        .initDevice()
                        .printList(list);
            }
        }

        needWait = false;
        if(saleType ==0){
            AppManager.geInstance().removeActivity("SaleActivity");
        }else{
            AppManager.geInstance().removeActivity("RefundActivity");
            AppManager.geInstance().removeActivity("RefundDialog");
            AppManager.geInstance().removeActivity("RefundYZActivity");
        }
        if(fromType==1){
            Intent intent = new Intent(this, CateringMainActivity.class);
            startActivity(intent);
        }else {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
        }
        finish();
        ErpCommonData.ticketInfo = new TicketInfo();
        ErpCommonData.oldTicket = new TicketInfo();
        setAdPresentation(3);
    }
    /**
     * 打印预览
     */
    public void showPrintDialog(final TicketInfo backTicket){

        AlertDialog.Builder builder=new AlertDialog.Builder(PayActivity.this);
        final AlertDialog dialog=builder.create();
        View view = LayoutInflater.from(PayActivity.this).inflate(R.layout.dialog_print,null);
        final TextView tv_title=view.findViewById(R.id.tv_dialog_title_name);

        final TextView tv_name=view.findViewById(R.id.tv_name);
        final Button bt_submit=view.findViewById(R.id.bt_submit);
        tv_title.setText("打印预览");
        List<String> list = TicketFormat.createTicketFormat(backTicket, false, 0);
        StringBuffer buffer=new StringBuffer();
        for (String content : list) {
            if (content.contains("|")) {
                String[] aa = content.split("\\|");
                for (int i = 0; i < aa.length; i++) {
                    buffer.append(aa[i] + "\n");
                }
            } else if (content.contains("@@@")) {
                String temp = content.substring(3, content.length());
                buffer.append(temp+ "\n");
            } else if (content.contains("&&&")) {
                String temp = content.substring(3, content.length());
                buffer.append(temp+ "\n");
            } else {
                buffer.append(content.trim()+ "\n");
            }
        }
        tv_name.setText(buffer.toString());
        bt_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                print(backTicket);
            }
        });

        dialog.setView(view,0,0,0,0);
        dialog.setCancelable(false);
        dialog.show();
    }

}
